package transaction

import (
	"bytes"
	"crypto/x509"
	"encoding/pem"
	"fmt"
)

func decodeSerializedIdentity(creator []byte) (string, error) {
	certStart := bytes.Index(creator, []byte("-----BEGIN"))
	if certStart == -1 {
		return "", fmt.Errorf("No certificate found")
	}
	certText := creator[certStart:]
	bl, _ := pem.Decode(certText)
	if bl == nil {
		return "", fmt.Errorf("Could not decode the PEM structure")
	}

	cert, err := x509.ParseCertificate(bl.Bytes)
	if err != nil {
		return "", err
	}
	uname := cert.Subject.CommonName
	return uname, nil
}

func GetX509CertByBytes(creator []byte) (*x509.Certificate, error) {
	certStart := bytes.Index(creator, []byte("-----BEGIN"))
	if certStart == -1 {
		return nil, fmt.Errorf("No certificate found")
	}
	certText := creator[certStart:]
	bl, _ := pem.Decode(certText)
	if bl == nil {
		return nil, fmt.Errorf("Could not decode the PEM structure")
	}

	cert, err := x509.ParseCertificate(bl.Bytes)
	if err != nil {
		return nil, err
	}
	return cert, nil
}
